package com.sl.sdn.util;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.stream.StreamUtil;
import cn.hutool.core.util.NumberUtil;
import com.sl.sdn.dto.OrganDTO;
import com.sl.sdn.dto.TransportLineNodeDTO;
import com.sl.sdn.enums.OrganTypeEnum;
import org.neo4j.driver.Record;
import org.neo4j.driver.internal.value.PathValue;
import org.neo4j.driver.types.Path;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class TransportLineUtil {

    private TransportLineUtil() {

    }

    public static TransportLineNodeDTO mappedRecord(Record record){
        PathValue pathValue = (PathValue) record.get(0);
        Path path = pathValue.asPath();
        TransportLineNodeDTO nodeDTO = new TransportLineNodeDTO();
        List<OrganDTO> organDTOS = StreamUtil.of(path.nodes())
                .map(node -> {
                    Map<String, Object> map = node.asMap();
                    OrganDTO organDTO = BeanUtil.toBeanIgnoreError(map, OrganDTO.class);
                    OrganTypeEnum organTypeEnum = OrganTypeEnum.valueOf(CollUtil.getFirst(node.labels()));
                    organDTO.setType(organTypeEnum.getCode());
                    organDTO.setLatitude(BeanUtil.getProperty(map.get("location"), "y"));
                    organDTO.setLongitude(BeanUtil.getProperty(map.get("location"), "x"));
                    return organDTO;
                })
                .collect(Collectors.toList());

        double cost = StreamUtil.of(path.relationships())
                .mapToDouble(relationship -> {
                    Map<String, Object> map = relationship.asMap();
                    return Convert.toDouble(map.get("cost"), 0d);
                })
                .sum();
        double costValue = NumberUtil.round(cost, 2).doubleValue();
        nodeDTO.setNodeList(organDTOS);
        nodeDTO.setCost(costValue);
        return nodeDTO;
    }
}
